package com.hanZhe.codeurl;

import com.hanZhe.bean.Product;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by shw on 2018/1/24.
 */

@Controller
public class GetUrlCode {

    @RequestMapping(value = "/getUrlCode", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView weixin_pay(Product product, HttpServletRequest request) throws Exception {

        ModelAndView modelAndView=new ModelAndView();

        // 账号信息
        String appid = PayConfigUtil.APP_ID;  // 微信支付分配的公众号id，公众号orpid即为appid
        String mch_id = PayConfigUtil.MCH_ID; // 微信支付分配的商户号
        String key = PayConfigUtil.API_KEY; // key

        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;

        // 获取发起电脑 ip
        String spbill_create_ip = PayConfigUtil.CREATE_IP;
        // 回调接口
        String notify_url = PayConfigUtil.NOTIFY_URL;
        String trade_type = "NATIVE";

        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", appid);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);

        packageParams.put("body", product.getBody());
        packageParams.put("out_trade_no", product.getOut_trade_no());
        packageParams.put("total_fee", product.getOrder_price());

        packageParams.put("spbill_create_ip", spbill_create_ip);
        packageParams.put("notify_url", notify_url);
        packageParams.put("trade_type", trade_type);

        String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);
        packageParams.put("sign", sign);

        String requestXML = PayCommonUtil.getRequestXml(packageParams);

        String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);

        Map map = XMLUtil.doXMLParse(resXml);

        String urlCode = (String) map.get("code_url");

        modelAndView.setViewName("payment");

        modelAndView.addObject("urlCode",urlCode);

        return modelAndView;
    }
}
